package springmvcdemo.controller;


import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.web.bind.annotation.*;

@RequestMapping("/test")
@RestController
public class Controller {
    //1.获取cookie
    @RequestMapping("/test1")
    public String getCookies(HttpServletRequest request) {
        //request里面就保存了http请求中的所有内容，现在我们只需要获取cookie即可
        Cookie[] cookies = request.getCookies();//获取cookie中所有的kv键值对
        //2.判断一下
        if(cookies != null) {
            for(Cookie cookie : cookies) {
                System.out.println(cookie.getName()+"："+cookie.getValue());
            }
        }
        return "获取Cookie成功";
    }
    @RequestMapping("/test2")
    public String getCookies2(@CookieValue("love") String value) {
        //获取cookie中键为love的值，此时的值就存取在value中了
        System.out.println("love："+value);
        return "获取love成功";
    }
    //2.设置session
    @RequestMapping("/setSession")
    public String setSession(HttpServletRequest request) {
        //客户端调用该函数后，就可以给该客户端存储session。下面算是拿到了服务器和客户端的session会话
        //当getSession()的参数为true时，如果session对象不存在，就会创造一个空的session对象，否则返回
        HttpSession session = request.getSession(true);//查看该客户端是否有seession存在
        session.setAttribute("name","zhangsan");
        session.setAttribute("age","18");
        session.setAttribute("sex","男");
        return "设置session成功";
    }
    //3.获取session
    @RequestMapping("/getSession1")
    public String getSession(HttpServletRequest request) {
        //参数为false,如果session不存在，返回null
        HttpSession session = request.getSession(false);
        if(session == null) return "session为null，获取失败";
        System.out.println("姓名："+session.getAttribute("name"));
        System.out.println("年龄："+session.getAttribute("age"));
        System.out.println("性别："+session.getAttribute("sex"));
        return "session获取成功";
    }
    @RequestMapping("/getSession2")
    public String getSession(HttpSession session) {
        //session == request.getSession()
        System.out.println("姓名："+session.getAttribute("name"));
        System.out.println("年龄："+session.getAttribute("age"));
        System.out.println("性别："+session.getAttribute("sex"));
        return "session获取成功";
    }
    @RequestMapping("/getSession3")
    public String getSession3(@SessionAttribute(value = "name",required = false) String name) {
        //获取指定session,name是必传参数，age是可选
        System.out.println("name="+name);
        return "获取指定session成功";
    }
    @RequestMapping("/getHeader")
    public String getHeader(HttpServletRequest request) {
        String UserAgent = request.getHeader("User-Agent");
        System.out.println();
        return "User-Agent="+UserAgent;
    }
    @RequestMapping("/getHeader2")
    public String getHeader2(@RequestHeader("User-Agent") String UserAgent) {
        System.out.println(UserAgent);
        return UserAgent;
    }




}
